﻿using DAL;
using IBLL;
using IDAL;
using Models;
using Models.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class MenuInfoBLL : IMenuInfoBLL
    {
        #region 构造函数
        private IMenuInfoDAL _menuInfoDAL;//菜单表数据访问
        private UnmanContexts _dbContext;//数据上下文
        private IR_RoleInfo_MenuInfoDAL _r_RoleInfo_MenuInfoDAL;//
        private IEmployee_RoleInfoDAL _Employee_RoleInfoDAL;//

        public MenuInfoBLL(
            UnmanContexts dbContext
            , IMenuInfoDAL menuInfoDAL
            , IEmployee_RoleInfoDAL employee_RoleInfoDAL
            , IR_RoleInfo_MenuInfoDAL r_RoleInfo_MenuInfoDAL
            )
        {
            _dbContext = dbContext;
            _menuInfoDAL = menuInfoDAL;
            _Employee_RoleInfoDAL = employee_RoleInfoDAL;
            _r_RoleInfo_MenuInfoDAL = r_RoleInfo_MenuInfoDAL;
        }

        #endregion

        #region 获取菜单列表（GetMenuInfos）--分页
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">每页几条数据</param>
        /// <param name="title">菜单标题</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        public List<GetMenuInfosDTO> GetMenuInfos(int page, int limit, string title, out int count)
        {
            //链表查
            var data = from m in _dbContext.MenuInfo.Where(m => m.IsDalete == false)
                       join m2 in _dbContext.MenuInfo.Where(m => m.IsDalete == false)
                       on m.ParentId equals m2.Id
                       into TempMM
                       from mm in TempMM.DefaultIfEmpty()
                       select new GetMenuInfosDTO
                       {
                           Id = m.Id,
                           Title = m.Title,
                           Description = m.Description,
                           Level = m.Level,
                           Sort = m.Sort,
                           Href = m.Href,
                           Icon = m.Icon,
                           Target = m.Target,
                           CreateTime = m.CreateTime,

                           ParentId = mm.Id,
                           ParentName = mm.Title
                       };

            //标题
            if (!string.IsNullOrWhiteSpace(title))
            {
                data = data.Where(m => m.Title.Contains(title));
            }
            //数据总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(r => r.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;
        }
        #endregion

        #region 获取菜单列表（GetMenuInfo）
        /// <summary>
        ///  获取菜单列表的方法
        /// </summary>
        /// <returns></returns>
        public List<GetMenuInfosDTO> GetMenuInfo()
        {
            List<GetMenuInfosDTO> menuList = _menuInfoDAL.GetEntities()
                                                         .Where(m => m.IsDalete == false)
                                                         .Select(m => new GetMenuInfosDTO
                                                         {
                                                             Id = m.Id,
                                                             Title = m.Title,
                                                         })
                                                         .ToList();
            return menuList;
        }

        #endregion

        #region 返回父级菜单下拉列表数据（GetSelectOptions）
        /// <summary>
        /// 返回父级菜单下拉列表数据(GetSelectOptions)
        /// </summary>
        /// <returns></returns>
        public object GetSelectOptions()
        {
            //父级
            var parentSelect = _dbContext.MenuInfo.Where(m => !m.IsDalete)
                                                        .Select(m => new
                                                        {
                                                            value = m.Id,
                                                            title = m.Title
                                                        }).ToList();
            //最后返回数据
            var data = new
            {
                parentSelect
            };
            return data;
        }
        #endregion

        #region 新增菜单的方法（CreateMenuInfoInfo）
        /// <summary>
        /// 新增菜单的方法
        /// </summary>
        /// <param name="menuInfo">新增的菜单实体</param>
        /// <param name="msg">返回的信息</param>
        /// <returns></returns>
        public bool CreateMenuInfo(MenuInfo menuInfo, out string msg)
        {
            //非空判断
            if (string.IsNullOrWhiteSpace(menuInfo.Title))
            {
                msg = "标题不能为空！";
                return false;
            }
            //查询判断是否重复
            MenuInfo oldEntity = _menuInfoDAL.GetEntities().FirstOrDefault(t => t.Title == menuInfo.Title);
            if (oldEntity != null)
            {
                msg = "标题已经存在！";
                return false;
            }
            //给对象补全属性
            menuInfo.Id = Guid.NewGuid().ToString();
            menuInfo.CreateTime = DateTime.Now;
            //提交到数据库
            bool isSuccess = _menuInfoDAL.CreateEntity(menuInfo);
            //返回结果
            msg = isSuccess ? "添加菜单成功" : "添加菜单失败";
            return isSuccess;
        }

        #endregion

        #region 根据id获取详情（GetMenuInfoById）
        /// <summary>
        /// 根据id获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MenuInfo GetMenuInfoById(string id)
        {
            return _menuInfoDAL.GetEntityById(id);
        }

        #endregion

        #region 编辑菜单的方法（UpdateMenuInfo）
        /// <summary>
        /// 编辑/修改菜单的方法（UpdateMenuInfo）
        /// </summary>
        /// <param name="menuInfo">编辑的菜单实体</param>
        /// <param name="msg">返回的信息</param>
        /// <returns></returns>
        public bool UpdateMenuInfo(MenuInfo menuInfo, out string msg)
        {
            //非空判断
            if (string.IsNullOrWhiteSpace(menuInfo.Title))
            {
                msg = "标题不能为空";
                return false;
            }
            //查询旧数据
            MenuInfo oldEntity = _menuInfoDAL.GetEntityById(menuInfo.Id);
            if (oldEntity == null)
            {
                msg = "标题不存在！";
                return false;
            }
            //判断标题是否有修改
            if (oldEntity.Title != menuInfo.Title)
            {
                //查找数据库是否已经有该名字的标题
                var entity = _menuInfoDAL.GetEntities().FirstOrDefault(m => m.Title == menuInfo.Title);
                if (entity != null)
                {
                    msg = "标题重复了！";
                    return false;
                }
            }
            //赋值
            oldEntity.Title = menuInfo.Title;
            oldEntity.Description = menuInfo.Description;
            oldEntity.Level = menuInfo.Level;
            oldEntity.Sort = menuInfo.Sort;
            oldEntity.Href = menuInfo.Href;
            oldEntity.ParentId = menuInfo.ParentId;
            oldEntity.Icon = menuInfo.Icon;
            oldEntity.Target = menuInfo.Target;
            bool isSuccess = _menuInfoDAL.UpdateEntity(oldEntity);//更新部门到数据库
            msg = isSuccess ? "更新成功！" : "更新失败！";//返回的消息，三元表达式
            return isSuccess;
        }
        #endregion

        #region  菜单软删除的方法（DeleteMenuInfo）
        /// <summary>
        /// 菜单软删除的接口
        /// </summary>
        /// <param name="id">被删除的菜单id</param>
        /// <returns></returns>
        public bool DeleteMenuInfo(string id)
        {
            //根据id查菜单是否存在
            MenuInfo menuInfo = _menuInfoDAL.GetEntityById(id);
            if (menuInfo == null)
            {
                return false;
            }
            //修改菜单的状态
            menuInfo.IsDalete = true;
            menuInfo.DeleteTime = DateTime.Now;
            //返回结果
            return _menuInfoDAL.UpdateEntity(menuInfo);
        }

        #endregion

        #region  菜单批量软删除的方法（DeleteMenuInfo）
        /// <summary>
        /// 菜单批量软删除的接口
        /// </summary>
        /// <param name="ids">被删除的菜单id集合</param>
        /// <returns></returns>
        public bool DeleteMenuInfo(List<string> ids)
        {
            foreach (var id in ids)
            {
                //根据id查菜单是否存在
                MenuInfo menuInfo = _menuInfoDAL.GetEntityById(id);
                if (menuInfo == null)
                {
                    continue;//跳出本次循环
                }
                menuInfo.IsDalete = true;
                menuInfo.DeleteTime = DateTime.Now;
                //执行修改
                _menuInfoDAL.UpdateEntity(menuInfo);
            }
            return true;
        }

        #endregion

        #region 获取菜单根据用户id的方法（GetMenus）
        /// <summary>
        /// 根据菜单，根据用户id
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public List<HomeMenuInfoDTO> GetMenus(string userId)
        {
            //先获取角色的id集                                  select RoleId from R_UserInfo_RoleInfo where UserId=''
            List<string> roleIds = _Employee_RoleInfoDAL.GetEntities().Where(x => x.StaffId == userId).Select(x => x.RoleId).ToList();
            //通过角色查询可访问的菜单id集
            List<string> menuIds = _r_RoleInfo_MenuInfoDAL.GetEntities().Where(x => roleIds.Contains(x.RoleId)).Select(x => x.MenuId).ToList();
            //获取当前用户能够访问的所有菜单集
            List<MenuInfo> allMenus = _menuInfoDAL.GetEntities().Where(x => menuIds.Contains(x.Id)).OrderBy(x => x.Sort).ToList();
            //找顶级菜单
            List<HomeMenuInfoDTO> topMenus = allMenus.Where(x => x.Level == 1).OrderBy(x => x.Sort).Select(x => new HomeMenuInfoDTO()
            {
                Id = x.Id,
                Title = x.Title,
                Href = x.Href,
                Target = x.Target,
                Icon = x.Icon
            }).ToList();
            #region 旧的二级子菜单方法
            ////通过遍历查询顶级菜单的子菜单
            //foreach (var item in topMenus)
            //{
            //    //找顶级菜单的子菜单
            //    List<HomeMenuInfoDTO> childMenus = allMenus.Where(x => x.ParentId == item.Id).Select(x => new HomeMenuInfoDTO()
            //    {
            //        Id = x.Id,
            //        Title = x.Title,
            //        Href = x.Href,
            //        Target = x.Target,
            //        Icon = x.Icon
            //    }).ToList();

            //    item.Child = childMenus;
            //}
            #endregion

            //调用递归方法
            GetChildMenus(topMenus, allMenus);

            return topMenus;
        }
        public void GetChildMenus(List<HomeMenuInfoDTO> parentMenu, List<MenuInfo> allMenus)
        {
            foreach (var item in parentMenu)
            {
                //找顶级菜单的子菜单
                List<HomeMenuInfoDTO> childMenus = allMenus.Where(x => x.ParentId == item.Id).Select(x => new HomeMenuInfoDTO()
                {
                    Id = x.Id,
                    Title = x.Title,
                    Href = x.Href,
                    Target = x.Target,
                    Icon = x.Icon
                }).ToList();
                //递归
                GetChildMenus(childMenus, allMenus);

                item.Child = childMenus;
            }
        }
        #endregion

    }
}
